﻿Imports System.Runtime.CompilerServices
Imports System.Text.RegularExpressions
Imports System.Windows.Interop

Public Module ExtensionModule

    <Extension()> _
    Public Sub MoveToCenter(ByVal dialog As Window)

        Dim owner = dialog.Owner
        If owner Is Nothing Then
            Exit Sub
        End If

        Dim left = owner.Left + (owner.ActualWidth - dialog.ActualWidth) / 2
        Dim top = owner.Top + (owner.ActualHeight - dialog.ActualHeight) / 2

        dialog.Left = left
        dialog.Top = top

        Dim handle = New WindowInteropHelper(owner).Handle
        Dim screen = System.Windows.Forms.Screen.FromHandle(handle)

        If dialog.Left < screen.WorkingArea.Left Then
            dialog.Left = screen.WorkingArea.Left
        ElseIf dialog.Left + dialog.ActualWidth > screen.WorkingArea.Left + screen.WorkingArea.Width Then
            dialog.Left = screen.WorkingArea.Left + screen.WorkingArea.Width - dialog.Width
        End If

        If dialog.Top < screen.WorkingArea.Top Then
            dialog.Top = screen.WorkingArea.Top
        ElseIf dialog.Top + dialog.ActualHeight > screen.WorkingArea.Top + screen.WorkingArea.Height Then
            dialog.Top = screen.WorkingArea.Top + screen.WorkingArea.Height - dialog.Height
        End If

    End Sub

End Module
